package com.my.netty.basic.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class EventLoopClient {
    /**
     * ChannelFuture
     */
    public static void main(String[] args) {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        //ChannelFuture是connect调用后立即返回的一个对象
        ChannelFuture channelFuture = new Bootstrap()
            .group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel sc) {
                    sc.pipeline().addLast(new StringEncoder());
                }
            })
            //1.连接到服务器
            //connect是一个异步方法，main线程调用后不代表连接建立完成，此时NIO线程真正去执行连接
            .connect(new InetSocketAddress("localhost", 8080));

        //2.1 方法1 主线程同步方法处理连接结果
        //sync方法阻塞等待NIO线程连接建立，sync之后可以正常获取Channel
//        channelFuture.sync();
//        Channel channel = channelFuture.channel();
//        log.info("已连接连接服务端 {}", channel);
//        channel.writeAndFlush("hello server");

        //2.2 方法2 异步处理，addListener（回调对象）方法处理连接结果
        channelFuture.addListener(new ChannelFutureListener() {
            //NIO线程连接建立完成后，会调用下面方法
            @Override
            public void operationComplete(ChannelFuture future) {
                //以下代码不再是主线程执行，而是NIO线程执行
                Channel channel = channelFuture.channel();
                log.info("已连接连接服务端 {}", channel);
                channel.writeAndFlush("hello server");
            }
        });

    }
}
